package com.atguigu.flink.chapter11;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

/**
 * @Author lzc
 * @Date 2022/10/31 10:41
 */
public class Flink05_SQL_BaseUse {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        DataStreamSource<WaterSensor> stream = env.fromElements(
            new WaterSensor("s1", 1L, 10),
            new WaterSensor("s2", 1L, 10),
            new WaterSensor("s1", 2L, 20),
            new WaterSensor("s1", 3L, 30),
            new WaterSensor("s1", 4L, 40),
            new WaterSensor("s1", 5L, 50)
        );
        
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        
        Table table = tEnv.fromDataStream(stream);
        // 纯 sql 的方式才查询表
        //        tEnv.executeSql("sql语句: ddl dml中的增删改");
        //Table table = tEnv.sqlQuery("sql语句: 只执行查询语句");
        // 1. 查询未注册的表
        /*tEnv
            .sqlQuery("select id, sum(vc) from " + table + " group by id")
            .execute()
            .print();
        */
        // 2. 查询已注册的表
        tEnv.createTemporaryView("sensor", table);
        tEnv
            .sqlQuery("select id, sum(vc) from sensor group by id")
            .execute()
            .print();
        
        
        
    }
}
/*
TableApi

SQL

 */